package longrise.phone.com.bjjt_jyb.compensate;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;

import java.util.ArrayList;
import java.util.List;

import longrise.phone.com.bjjt_jyb.Application.BaseApplication;
import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.Utils.UiUtil;


public class SelectAccidentView extends LFView implements OnClickListener {

    private Context mContext = null;
    private View mView = null;
    private TextView title = null;
    // 返回按钮
    private LinearLayout back = null;
    // 补充情形
    private EditText supplementaryCase_text = null;
    // 确定
    private Button accident_confirm = null;

    // 当前选择
    private int currentSelectType = -1;
    private int selecteditem = 0;
    // 当前选填描述
    private String desc = null;
    // 全局applicaton
    private BaseApplication mApplication;

    // 历史标志
    private String appCaseno;
    private String kckpUserType;
    private Integer takepicKind=-1;//

    public SelectAccidentView(Context c, String caseNo,Integer takepicKind) {
        super(c);
        this.mContext = c;
        this.mApplication = (BaseApplication) c.getApplicationContext();
        this.appCaseno = caseNo;
        this.takepicKind=takepicKind;
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public View getView() {

        return mView;
    }

    @Override
    public void init() {
        kckpUserType = mApplication.getKckpUserType();
        LayoutInflater inflater = null;
        if (null != mContext) {
            inflater = LayoutInflater.from(mContext);
        }
        if (null != inflater) {
            mView = inflater.inflate(R.layout.responsibility_select_accident,
                    null);
        }
        if (null == mView) {
            return;
        }

        title = (TextView) mView.findViewById(R.id.tv_title);
        accident_confirm = (Button) mView.findViewById(R.id.accident_confirm);
        back = (LinearLayout) mView.findViewById(R.id.hn_btn_back);
        ListView lv_select = (ListView) mView.findViewById(R.id.lv_select);
        if(null!= kckpUserType &&"9".equals(kckpUserType)){
            // 设置标题
            if (null != title) {
                title.setText("选择事故形态");
            }
            lv_select.setVisibility(View.VISIBLE); //交警才有事故形态
        }else {
            // 设置标题
            if (null != title) {
                title.setText("事故情况描述");
            }
            lv_select.setVisibility(View.GONE); //协警只有事故描述
        }
        supplementaryCase_text = (EditText) mView
                .findViewById(R.id.supplementaryCase_text);
        regEvent(true);
        initProcessList();
        MySelectAdapter adapter = new MySelectAdapter(mContext);
        lv_select.setAdapter(adapter);
        supplementaryCase_text.setFilters(new InputFilter[]{new MaxLengthFilter(80, mContext)});
    }
    //增加输入长度的限制提示
    private static class MaxLengthFilter implements InputFilter {
        private final int mMax;
        private Context context;

        private MaxLengthFilter(int max, Context context) {
            mMax = max;
            this.context = context;
        }

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            int keep = mMax - (dest.length() - (dend - dstart));
            if (keep < (end - start)) {
                UiUtil.showToast(context, "最多只能写80字！");
            }
            if (keep <= 0) {
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }
    }

    private void regEvent(boolean flag) {
        if (null != back) {
            back.setOnClickListener(flag ? this : null);
        }
        if (null != accident_confirm) {
            accident_confirm.setOnClickListener(flag ? this : null);
        }
    }

    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void OnDestroy() {
        regEvent(false);
        mView = null;
        title = null;
        back = null;
        currentSelectType = -1;
        desc = null;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.hn_btn_back:
                closeForm();
                OnDestroy();
                break;
            case R.id.accident_confirm:
                    accidentInfo();
                break;
            default:
                break;
        }
    }

    private List<ProcessInfo> userProcessInfos;
    private String[] accidentAll= new String[]{"同车道行驶的车辆追撞前车尾部的","借道通行或变更车道时未让正常行驶的车辆先行的","通过没有交通信号的交叉路口时，未让优先通行的一方先行的",
            "相对方向来车左转弯车辆未让直行车辆，或右转弯车辆未让左转弯车辆先行的","不按照交通信号指示通行的","交叉路口先放行车辆未驶离路口时，后放行车辆未让行的",
            "在道路上会车不按规定通行或让行的","逆向行驶的","不按规定强行超车的","行经交叉路口、窄桥、弯道、陡坡、隧道、人行横道路段时超车的","在只有一条机动车道的道路上，从前车右侧超越的",
            "遇前方车辆停车排队或者缓慢行驶时，从前方车辆两侧穿插或者超越行驶的","在车道减少的路口、路段，遇前方车辆停车排队或者缓慢行驶的，不依次交替驶入路口、路段的","在禁止掉头或者在允许掉头的地方未让正常行驶车辆先行的",
            "倒车、溜车、车辆失控与其他车辆发生碰撞的","在专用车道内行驶或驶入禁行线的","开关车门造成交通事故的","车辆进出停车场、停车位或者由路边、非机动车道进出道路与正常行驶车辆、停放车辆发生交通事故的，及在机动车道上违法停车的",
            "车辆装载货物超长、超宽、超高部分或者货物在遗洒、飘散过程中导致交通事故的","不按规定牵引车辆造成交通事故的","单方发生交通事故的","未确保安全的其他情形"};
    private void initProcessList() {
        //创建集合为CopyOnWriteArrayList,可以防止在集合遍历的过程中抛出ConcurrentModificationException(并发修改异常)
        //底层两个数组,一个源数据,一个拷贝数组,源数组用于遍历,拷贝数组用于修改
       // userProcessInfos = new CopyOnWriteArrayList<ProcessInfo>();
        userProcessInfos = new ArrayList<>();
        for(int i=0;i<22;i++){
            userProcessInfos.add(new ProcessInfo(accidentAll[i],false));
        }
    }

    private class MySelectAdapter extends BaseAdapter {
        private final Context context;

        public MySelectAdapter(Context context) {
            this.context = context;
        }
        @Override
        public int getCount() {
            return userProcessInfos.size();
        }

        @Override
        public Object getItem(int position) {

            return null;
        }

        @Override
        public long getItemId(int position) {

            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder ;
                if (convertView != null) {
                    holder = (ViewHolder) convertView.getTag();
                } else {
                    convertView = LayoutInflater.from(context).inflate(R.layout.lv_process_list_item, null);
                    holder = new ViewHolder();
                    holder.tv_process_name = (TextView) convertView.findViewById(R.id.tv_process_name);
                    holder.cb_checked = (CheckBox) convertView.findViewById(R.id.cb_checked);
                    convertView.setTag(holder);
                }
            final ProcessInfo info = userProcessInfos.get(position);
                holder.cb_checked.setChecked(info.isChecked());
                holder.cb_checked.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        if(info.isChecked()){
                            cb.setChecked(false);
                            info.setChecked(cb.isChecked());
                        }
                        //遍历选中的条目
                        countselecttotleitem();
                        if(selecteditem>2){
                            UiUtil.showToast(mContext,"事故形态最多选择三个");
                            cb.setChecked(false);
                            info.setChecked(cb.isChecked());
                            return;
                        }
                        // 将勾选状态存入info中
                        info.setChecked(cb.isChecked());
                    }
                });
                holder.tv_process_name.setText(info.getPackageName());
            return convertView;
            }

    }

    private class ViewHolder {
        private TextView tv_process_name;
        private CheckBox cb_checked;
    }


    private void accidentInfo() {
        clear();
        if(null!=kckpUserType&&"9".equals(kckpUserType)){
            if (currentSelectType == -1) {
                UiUtil.showToast(mContext, "请选择事故形态");
                return;
            }
        }
        desc = supplementaryCase_text.getText().toString();
        if(1==takepicKind){
            //进入机动车事故填写界面
            AccidentLoadingView accidentloadingview = new AccidentLoadingView(mContext, appCaseno,
                    mySelect, desc,2);
            FrameworkManager.getInstance().showNewForm(mContext, accidentloadingview);
        }else if(2==takepicKind){
            //进入机动车与非机动车事故填写
            AccidentLoadingViewNew accidentloadingviewnew = new AccidentLoadingViewNew(mContext, appCaseno,
                    mySelect, desc);
            FrameworkManager.getInstance().showNewForm(mContext, accidentloadingviewnew);
        }else {
            //进入非动车与非机动车事故填写
            AccidentLoadingViewNewTwo accidentloadingviewnewtwo = new AccidentLoadingViewNewTwo(mContext, appCaseno,
                    mySelect, desc);
            FrameworkManager.getInstance().showNewForm(mContext, accidentloadingviewnewtwo);
        }

    }
    private String mySelect;


    /**
     * 当处于选择状态应该怎么做
     */
    private void clear(){
        for(int i=0;i<userProcessInfos.size();i++){
            if(userProcessInfos.get(i).isChecked()){
                currentSelectType=i+1;//当这个选中，那么事故的类型就是他的index
                if(null!=mySelect){
                    mySelect=mySelect+","+currentSelectType;
                }else {
                    mySelect=String.valueOf(currentSelectType);
                }
            }
        }
    }
    private void countselecttotleitem() {
        selecteditem=0;
        for(int i=0;i<userProcessInfos.size();i++){
            if(userProcessInfos.get(i).isChecked()){
                selecteditem++;
            }
        }
    }
}
